package jsi.spring;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

@Repository
@Transactional
public class OsobaServiceSimpleImpl implements OsobaDao, OsobaService{

	protected SessionFactory mySessionFactory;

	TransactionTemplate tt;
	
	public OsobaServiceSimpleImpl() {
	}

	public void deleteAll(){
		mySessionFactory.getCurrentSession().createQuery("delete from Osoba").executeUpdate();
	}

	public void saveOsoba(Osoba o){
		mySessionFactory.getCurrentSession().saveOrUpdate(o);
	}

	public Osoba mergeOsoba(Osoba o){
		return (Osoba) mySessionFactory.getCurrentSession().merge(o);
	}

	@Transactional(readOnly = true)
	public Osoba findOsobaByName(String imie) {
		System.out.println("sf: " + mySessionFactory);
		List l = mySessionFactory.getCurrentSession().createQuery("from Osoba o where o.imie = :imie")
				.setString("imie", imie).list();
		if (l.size() == 0)
			return null;
		else
			return (Osoba) l.get(0);
	}

	public void setMySessionFactory(SessionFactory sf) {
		System.out.println("================================== setMysessionFacotry");
		mySessionFactory = sf;
	}
	
	public void setTt(TransactionTemplate tt){
		this.tt = tt;
	}
	
	public TransactionTemplate getTt(){
		return this.tt;
	}
	
	public void incOsobaAge(Osoba o){
		
	}
	
	public List<Osoba> getAllOsoba(){
		return mySessionFactory.getCurrentSession().createQuery("from Osoba").list();
	}
	
	public void saveTwoPersons(Osoba o1, Osoba o2){
		try {
			mySessionFactory.getCurrentSession().saveOrUpdate(o1);
			mySessionFactory.getCurrentSession().saveOrUpdate(o2);
		} catch (DataAccessException e) {
			throw e;
		}
	}
	
	public void saveTwoPersonsWithException(Osoba o1, Osoba o2, boolean throww) throws CheckedDataAccessException{
		
		mySessionFactory.getCurrentSession().saveOrUpdate(o1);
		if (throww) throw new CheckedDataAccessException("Controlled exception");
		mySessionFactory.getCurrentSession().saveOrUpdate(o2);
		
	}
	
	public static class CheckedDataAccessException extends Exception  {
		
		public CheckedDataAccessException() {
			super();
		}

		public CheckedDataAccessException(String message, Throwable cause) {
			super(message, cause);
		}

		public CheckedDataAccessException(String message) {
			super(message);
		}

		public CheckedDataAccessException(Throwable cause) {
			super(cause);
		}
		
	}
}
